<?php

class usercp_sections
{
	var $mode;
	
	var $valid = false;
	var $add = false;
	var $drivers = Array();
	var $logoManager = '';
	var $teams = Array();
	var $items = Array();
	var $carOptions = '';
	var $teamOptions = '';

	function usercp_sections($mode)
	{
		$this->mode = $mode;
		
		if($mode == 'myteams' && isset($_POST['leaveTeam']) && isset($_POST['teamid']) && isset($_SESSION["valid_id"]))
		{
			$this->removeTeamMembership();
		}
		
		if($mode == 'teamadmin' && isset($_POST['editTeamDetails']) && isset($_POST['itemID']) && isset($_SESSION["valid_id"]))
		{
			$this->saveTeamDetails();
		}
		else if($mode == 'teamadmin' && isset($_POST['addTeamDetails']) && isset($_SESSION["valid_id"]))
		{
			$this->addTeamDetails();
		}
		else if($mode == 'teamadmin' && isset($_POST['saveTeamDriver']) && isset($_SESSION["valid_id"]))
		{
			$this->saveTeamDriver();
		}
		else if($mode == 'teamadmin' && isset($_POST['removeTeamDriver']) && isset($_SESSION["valid_id"]))
		{
			$this->removeTeamDriver();
		}
		else if($mode == 'mychampionships' && isset($_POST['saveChamp']) && isset($_SESSION["valid_id"]))
		{
			$this->saveMyChampionshipSettings();
		}
		else if($mode == 'mychampionships' && isset($_POST['multiDriverEntry']) && isset($_SESSION["valid_id"]))
		{
			$this->saveMultiDriverEntry();
		}
		
		if($mode == 'myteams')
		{
			$this->setupMyTeams();
		}
		else if($mode == 'teamadmin')
		{
			$this->setupTeamAdmin();
		}
		else if((isset($_POST['editChamp']) ||isset($_POST['uploadLogo']) || isset($_POST['removeLogo'])) && $mode == 'mychampionships')
		{
			$this->setupEditMyChampionship();
		}
		else if(isset($_POST['editChampDrivers']) && $mode == 'mychampionships' && isset($_POST['champid']) && is_numeric($_POST['champid']) && isset($_POST['teamid']) && is_numeric($_POST['teamid']))
		{
			$this->setupEditMyChampionshipDrivers();
		}
		else if($mode == 'mychampionships')
		{
			$this->setupMyChampionships();
		}
		else if($mode == 'mycurrentevents')
		{
			include_once('includes/usercp_events.php');
			$this->items[] = new usercp_events(true);
		}
		else if($mode == 'mypastevents')
		{
			include_once('includes/usercp_events.php');
			$this->items[] = new usercp_events(false);
		}
		else if($mode == 'createincident')
		{
			include_once('includes/incident_create.php');
			$this->items[] = new incident_create();
		}
		else if($mode == 'myincidents')
		{
			include_once('includes/incident_overview.php');
			$this->items[] = new incident_overview();
		}
		else if($mode == 'incidentadmin')
		{
			include_once('includes/incident_admin.php');
			if(isset($_GET['champ']))
			{
				$this->items[] = new incident_admin_champ($_GET['champ']);
			}
			else if(isset($_GET['event']))
			{
				$this->items[] = new incident_admin_event($_GET['event']);
			}
			else if(isset($_GET['incident']))
			{
				$this->items[] = new incident_admin_view($_GET['incident']);
			}
			else
			{
				$this->items[] = new incident_admin();
			}
		}
		else if($mode == 'viewincident' && isset($_GET['id']) && is_numeric($_GET['id']))
		{
			include_once('includes/incident_overview.php');
			$this->items[] = new incident_detail($_GET['id']);
		}
		else
		{
			$this->mode = 'myteams';
			$this->setupMyTeams();
		}
		
	}
	function render()
	{
		foreach($this->items as $value)
		{
			$value->render();
		}
		if($this->mode == 'myteams')
		{
			$this->renderMyTeams();
		}
		else if($this->mode == 'teamadmin')
		{
			$this->renderTeamAdmin();
		}
		else if((isset($_POST['editChamp']) ||isset($_POST['uploadLogo']) || isset($_POST['removeLogo']))  && $this->mode == 'mychampionships')
		{
			$this->renderEditMyChampionships();
		}
		else if(isset($_POST['editChampDrivers']) && $this->mode == 'mychampionships' && isset($_POST['champid']) && is_numeric($_POST['champid']) && isset($_POST['teamid']) && is_numeric($_POST['teamid']))
		{
			$this->renderEditMyChampionshipDrivers();
		}
		else if($this->mode == 'mychampionships')
		{
			$this->renderMyChampionships();
		}
	}
	
	function removeTeamMembership()
	{
		global $www_path, $lang, $db;
		include_once('includes/addMessage.php');
	
		$qThisUser = 'SELECT pf_drivername AS user_drivername FROM ' . DRIVERNAME_TABLE . ' where user_id = ' . $_SESSION["valid_id"];
		$qThisTeam = 'SELECT t_name FROM ' . TEAMS_TABLE . ' where t_id = ' . $_POST['teamid'];
		$qRemove = 'DELETE FROM ' . TEAMMEMBERS_TABLE . ' WHERE tm_driver = ' . $_SESSION["valid_id"] . ' AND tm_team = ' . $_POST['teamid'];	
		$res = $db->sql_query($qThisUser);
		if( $submitUser = $db->sql_fetchrow($res))
		{
			$res = $db->sql_query($qThisTeam);
			if( $thisTeam = $db->sql_fetchrow($res))
			{
				$db->sql_query($qRemove);
				$this->items[] = new addMessage(str_replace('{team}', $thisTeam['t_name'], $lang['UserCPLeaveTeamInfo']),
												str_replace('{driver}', $submitUser['user_drivername'], 
														str_replace('{team}', $thisTeam['t_name'], $lang['UserCPLeaveTeam'])));
			}	
			else
			{
				$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
			}
		}
		else
		{
			$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
		}
	}
	
	function saveTeamDetails()
	{
		global $lang, $db;
		include_once('includes/addMessage.php');
	
		$qUpd = "update  ". TEAMS_TABLE . " set t_name = '" . $_POST['teamname'] .
													  "', t_nationality = '" . $_POST['nationality'] .
													  "', t_website= '" . $_POST['website'] .
													  "', t_description= '" . $_POST['description'] .
													  "' WHERE t_id = " . $_POST['itemID'] ;
		$result = $db->sql_query($qUpd);
		
		$this->items[] = new addMessage(str_replace('{entry}', $_POST['teamname'], $lang['AdminUpdated']), $lang['AdminUpdatedTitle']);
	}
	
	function saveTeamDriver()
	{
		global $lang, $db;
		include_once('includes/addMessage.php');
				
		$valid = isset($_POST['driver']) && is_numeric($_POST['driver']) &&
				isset($_POST['itemID']) && is_numeric($_POST['itemID']);
		
		$_POST['admin'] = isset($_POST['admin']) ? $_POST['admin'] : 0;
		$_POST['approved'] = isset($_POST['approved']) ? $_POST['approved'] : 0;
		
		$_POST['admin'] = $_POST['admin'] == 1 ? 1 : 0;
		$_POST['approved'] = $_POST['approved'] == 1 ? 1 : 0;
	
		if($valid) 
		{
			$qSel = 'SELECT pf_drivername as user_drivername FROM ' . DRIVERNAME_TABLE . ' WHERE user_id = ' . $_POST['driver'];
			$result = $db->sql_query($qSel);
			if($row = $db->sql_fetchrow($result))
			{
				$qUpd = "update  ". TEAMMEMBERS_TABLE . " set tm_approved = " . $_POST['approved'] .
													  ", tm_admin = " . $_POST['admin'] .
													  " WHERE tm_driver = " . $_POST['driver'] . ' AND ' .
													  " tm_team = " . $_POST['itemID'];
				$db->sql_query($qUpd);
				$this->items[] = new addMessage(str_replace('{entry}', $row['user_drivername'], $lang['AdminUpdated']), $lang['AdminUpdatedTitle']);
			}
			else
			{
				$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
			}
		}
		else
		{
			$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
		}
	}
	
	function removeTeamDriver()
	{
		global $lang, $db;
		include_once('includes/addMessage.php');
				
		$valid = isset($_POST['driver']) && is_numeric($_POST['driver']) &&
				isset($_POST['itemID']) && is_numeric($_POST['itemID']);
			
		if($valid) 
		{
			$qSel = 'SELECT pf_drivername as user_drivername FROM ' . DRIVERNAME_TABLE . ' WHERE user_id = ' . $_POST['driver'];
			$result = $db->sql_query($qSel);
			if($row = $db->sql_fetchrow($result))
			{
				$qDel = "delete from ". TEAMMEMBERS_TABLE . " Where tm_team = " . $_POST['itemID'] . " AND tm_driver = " . $_POST['driver'];;
				$db->sql_query($qDel);
				$this->items[] = new addMessage(str_replace('{entry}', $row['user_drivername'], $lang['AdminRemoved']), $lang['AdminRemovedTitle']);
			}
			else
			{
				$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
			}
		}
		else
		{
			$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
		}
	}
	
	function addTeamDetails()
	{
		global $lang, $db;
		include_once('includes/addMessage.php');
	
		if($_POST['teamname'] != '')
		{
			$qTeam = "insert into  ". TEAMS_TABLE . " (t_name, t_nationality, t_website, t_description, t_parent) values('" . 
							$_POST['teamname'] . "', '" . $_POST['nationality'] . "', '" . $_POST['website'] . "', '" . $_POST['description'] . "', " . $_POST['parent'] .  ")" ;
			$db->sql_query("LOCK TABLES ". TEAMS_TABLE . "  WRITE");
			$db->sql_query("SET AUTOCOMMIT = 0");
			$db->sql_query($qTeam);
			$insertID = $db->sql_nextid();
			$_POST['itemID'] = $insertID;
			$db->sql_query("COMMIT");
			$db->sql_query("SET AUTOCOMMIT = 1");
			$db->sql_query("UNLOCK TABLES");
			
			if($_POST['parent'] == 0)
			{
				$qMember = "insert into " . TEAMMEMBERS_TABLE . " VALUES( " .  $_SESSION["valid_id"] . ", " .  $insertID . ", 1, 1)";
				$db->sql_query($qMember);
			}
			
			$this->items[] = new addMessage(str_replace('{entry}', $_POST['teamname'], $lang['AdminAdded']), $lang['AdminAddedTitle']);
		}
		else
		{
			$this->items[] = new addMessage($lang['ErrorFieldsNotEntered'], $lang['ErrorTitle']);
		}
	}
	
	function setupMyTeams()
	{
		global $db, $lang;
		include_once('includes/addMessage.php');
		
		$q = 'select t_id, t_name, tm_approved, tm_admin from ' . TEAMS_TABLE . ', ' . TEAMMEMBERS_TABLE .
				' WHERE t_id = tm_team AND tm_driver = ' . $_SESSION["valid_id"] . ' ORDER BY t_name ASC';
		$res = $db->sql_query($q);
		while( $row = $db->sql_fetchrow($res))
		{
			$this->teams[] = $row;
		}
		
		$this->items[] = new addMessage($lang['UserCPTeamsInfo'],$lang['UserCPTeams']);
	}
	
	function setupMyChampionships()
	{
		global $db, $lang;
		include_once('includes/addMessage.php');
		
		$q = 'select c.c_id as champid, c.c_title, c.c_smallTitle, cs_no, cs_driver, cs_entryOwner, d_id, d_title, c.c_active, c.c_multiDriverEntryMin,' . 
					'(SELECT t.t_id FROM ' . TEAMS_TABLE . ' t WHERE t.t_id = cs_team LIMIT 0, 1) AS t_id,'.
					'(SELECT t.t_name FROM ' . TEAMS_TABLE . ' t WHERE t.t_id = cs_team LIMIT 0, 1) AS t_name,  ' . 
					'(SELECT ca.c_manufacturer FROM ' . CARS_TABLE . ' ca WHERE ca.c_id = cs_car LIMIT 0, 1) AS c_manufacturer,'.
					'(SELECT ca.c_model FROM ' . CARS_TABLE . ' ca WHERE ca.c_id = cs_car LIMIT 0, 1) AS c_model,'.
					'(SELECT ca.c_id FROM ' . CARS_TABLE . ' ca WHERE ca.c_id = cs_car LIMIT 0, 1) AS carid
				 FROM ' . CHAMPIONSHIPS_TABLE .' c, ' . CHAMPSIGNUPS_TABLE . '
				 LEFT JOIN ' . DIVISIONS_TABLE .' ON cs_div = d_id
				 WHERE cs_champ = c.c_id AND c_enabled = 1 AND cs_driver = ' . $_SESSION["valid_id"] .
				 ' ORDER BY c.c_lastRace DESC, c.c_title ASC';

		$res = $db->sql_query($q);
		while( $row = $db->sql_fetchrow($res))
		{
			if($row['d_id'] == '')
			{
				$row['d_id'] = 0;
				$row['d_title'] = $lang['Unassigned'];
			}
			
			$this->teams[] = $row;
		}
		
		$this->items[] = new addMessage($lang['UserCPChampsInfo'],$lang['Championships']);
	}
	
	function saveMyChampionshipSettings()
	{
		global $db, $lang;
		include_once('includes/addMessage.php');
		
		$updateTeam = '';
		$updateCar = '';
		
		//get our present settings
		$q = 'select c.c_id as champid, c.c_title, cs_no, d_id, d_title, c.c_teamChanging, c.c_carChanging, c.c_driversPerTeam, c.c_multipleCarsPerTeam, ' . 
					'(SELECT t.t_id FROM ' . TEAMS_TABLE . ' t WHERE t.t_id = cs_team LIMIT 0, 1) AS t_id,'.
					'(SELECT t.t_name FROM ' . TEAMS_TABLE . ' t WHERE t.t_id = cs_team LIMIT 0, 1) AS t_name,  ' . 
					'(SELECT ca.c_manufacturer FROM ' . CARS_TABLE . ' ca WHERE ca.c_id = cs_car LIMIT 0, 1) AS c_manufacturer,'.
					'(SELECT ca.c_model FROM ' . CARS_TABLE . ' ca WHERE ca.c_id = cs_car LIMIT 0, 1) AS c_model,'.
					'(SELECT ca.c_id FROM ' . CARS_TABLE . ' ca WHERE ca.c_id = cs_car LIMIT 0, 1) AS carid 
				 FROM ' . CHAMPIONSHIPS_TABLE .' c, ' . CHAMPSIGNUPS_TABLE . '
				 LEFT JOIN ' . DIVISIONS_TABLE .' ON cs_div = d_id
				 WHERE cs_champ = c.c_id AND cs_driver = ' . $_SESSION["valid_id"] . ' AND cs_champ = ' . $_POST['champid'] .
				 ' ORDER BY c.c_title ASC';
		
		$res = $db->sql_query($q);
		if( $row = $db->sql_fetchrow($res))
		{
			//team has changed
			if(!(($_POST['team'] == 0 && $row['t_id'] == '') || $_POST['team'] == $row['t_id']))
			{
				//if we're independent it's valid
				if($_POST['team'] == 0)
				{
					$updateTeam = 'yes';
					if(!(($_POST['car'] == 0 && $row['carid'] == '') || $_POST['car'] == $row['carid']))
					{
						//car has changed
						$updateCar = 'yes';
					}
				}
				else
				{
					$updateTeam = 1;
					//no multiple car teams, we have to restrict the car choice
					if($row['c_multipleCarsPerTeam'] == 0 && $row['c_carChanging'] == 1)
					{
						//will have to update car to the team car if required
						$updateCar = 'team';
					}
					else if(!(($_POST['car'] == 0 && $row['carid'] == '') || $_POST['car'] == $row['carid']))
					{
						//car has changed
						$updateCar = 'yes';
					}
					
				}
				
			}
			else if(!(($_POST['car'] == 0 && $row['carid'] == '') || $_POST['car'] == $row['carid']))
			{
				//car has changed
				$updateCar = 'yes';
			}
			
			
			if($updateTeam == 1)
			{
				$q_teams = 'SELECT t_id, t_name, ' . 
						'(SELECT c_id FROM ' . CHAMPSIGNUPS_TABLE . ', ' . CARS_TABLE . 
							' WHERE cs_driver = cs_entryOwner AND c_id = cs_car AND cs_team = t_id AND cs_champ = ' . $_POST['champid'] . ' LIMIT 0, 1) as t_carid, ' .
						'(SELECT count(*) FROM ' . CHAMPSIGNUPS_TABLE . ' WHERE cs_driver = cs_entryOwner AND  cs_team = t_id AND cs_champ = ' . $_POST['champid'] . 
							' LIMIT 0, 1) as tm_entries ' .
						' FROM ' . TEAMS_TABLE . ', ' . TEAMMEMBERS_TABLE . ' 
						  WHERE (t_id = tm_team OR tm_team = t_parent) AND tm_approved = 1 AND tm_driver = ' . $_SESSION['valid_id'] .' AND t_id = ' . $_POST['team'] . ' 
						  GROUP BY t_id
						  ORDER BY t_name';
				$res = $db->sql_query($q_teams);
				if( $t = $db->sql_fetchrow($res))
				{
					if($t['tm_entries'] < $row['c_driversPerTeam'] || $row['c_driversPerTeam'] == 0)
					{
						//valid team update
						$updateTeam = 'yes';
						//need to find out the 'team' car
						if($updateCar == 'team' && $t['t_carid'] != '')
						{
							$_POST['car'] = $t['t_carid'];
							$updateCar = 'yes';
						}
						else if($updateCar == 'team')
						{
							$updateCar = 'yes';
						}
					}
					else
					{
						$this->items[] = new addMessage($lang['ChampSignupFullTeam'],$lang['ErrorTitle']);
					}
				}
				else
				{
					$this->items[] = new addMessage($lang['DatabaseError'],$lang['ErrorTitle']);
					echo 1;
				}
			}
			
			$q = '';
			if($updateTeam == 'yes')
			{
				$q .= ' cs_team = ' . $_POST['team'];
			}
			
			if($updateCar == 'yes')
			{
				$q .= ($q == '' ? '' : ',') . ' cs_car = ' . $_POST['car'];
				
				//Check Division Value
				$qD = 'SELECT cl.c_defaultdiv 
					  FROM ' . CHAMP_CLASSES_TABLE . ' cl, ' . CARS_TABLE . ' c
					  WHERE c.c_class = cl.c_class AND c.c_id = ' . $_POST['car'] . ' AND cl.c_champid = ' . $_POST['champid'];
				$result = $db->sql_query($qD);
				if($row = $db->sql_fetchrow($result)) 
				{
					if($row['c_defaultdiv'] > 0)
						$q .= ', cs_div = ' . $row['c_defaultdiv'];
				}	  
					
			}
			
			if($q != '')
			{
				$q = 'UPDATE ' . CHAMPSIGNUPS_TABLE . ' SET ' . $q . ' WHERE cs_entryOwner = ' . $_SESSION['valid_id'] . ' AND cs_champ = ' . $_POST['champid'];
				$db->sql_query($q);
				if($db->sql_affectedrows() > 0)
				{
					$q = 'UPDATE ' . EVENTSIGNUPS_TABLE . ', ' . EVENTS_TABLE . ', ' . EVENTDATES_TABLE . ', ' . CHAMPSIGNUPS_TABLE . '
						  SET es_no = cs_no, es_team = cs_team, es_car = cs_car, es_division = cs_div
						  WHERE es_entryOwner = ' . $_SESSION['valid_id'] . ' AND cs_entryOwner = es_entryOwner AND ed_date > NOW() AND es_event = e_id AND ed_event = e_id
      						AND ed_division = cs_div AND cs_champ = e_championship AND e_championship = ' . $_POST['champid'];
					$db->sql_query($q);
					$this->items[] = new addMessage($lang['UserCPChampInfoSave'],$lang['ChampSignedUpTitle']);
					
				}
				else
				{
					$this->items[] = new addMessage($lang['DatabaseError'],$lang['ErrorTitle'] . '2');
				}
			}
			else
			{
				//nothing to update
				$this->items[] = new addMessage($lang['UserCPChampInfoNoChanges'],$lang['ChampSignedUpTitle']);
			}
			
			
		}
		else
		{
			$this->items[] = new addMessage($lang['DatabaseError'],$lang['ErrorTitle'] . '1');
		}
		
	}
	
	
	function saveMultiDriverEntry()
	{
		global $db, $lang;
		include_once('includes/addMessage.php');
				
		$valid = true;
		$drivers = Array();
		
		while (list ($key,$val) = @each ($_POST['driverSelect'])) 
		{ 
			$drivers[] = $val;
			if(! is_numeric($val))
			{
				$valid = false;
			}
		}
		
		if( ! $valid || sizeof($drivers) == 0 ||
			!isset($_POST['currentCaptain']) || ! is_numeric($_POST['currentCaptain']) || 
			!isset($_POST['champid']) || ! is_numeric($_POST['champid']) || 
			!isset($_POST['captainSelect']) || ! is_numeric($_POST['captainSelect']) || 
			!isset($_POST['champid']) || ! is_numeric($_POST['champid']) )
		{
			$this->items[] = new addMessage($lang['DatabaseError'],$lang['ErrorTitle']);
			$valid = false;
			return;
		}
		
		$currentEntry = Array();
		
		//get our present settings
		$qCurrent = 'SELECT * 
					 FROM ' . CHAMPSIGNUPS_TABLE . '
					 WHERE cs_driver = ' . $_POST['currentCaptain'] . ' AND cs_champ = ' . $_POST['champid'];
		//delete existing entries
		$qDelete = 'DELETE FROM ' . CHAMPSIGNUPS_TABLE . '
					 WHERE cs_entryOwner = ' . $_POST['currentCaptain'] . ' AND cs_champ = ' . $_POST['champid'];
		$db->sql_query("LOCK TABLES ". CHAMPSIGNUPS_TABLE . "  WRITE");
		$db->sql_query("SET AUTOCOMMIT = 0");
		$currentResult = $db->sql_query($qCurrent);		
		if( $currentEntry = $db->sql_fetchrow($currentResult))
		{
			$db->sql_query($qDelete);
		}
		else
		{
			$this->items[] = new addMessage($lang['DatabaseError'],$lang['ErrorTitle']);
			$valid = false;
		}
		$db->sql_query("COMMIT");
		$db->sql_query("SET AUTOCOMMIT = 1");
		$db->sql_query("UNLOCK TABLES");
		
		//get present details failed
		if(! $valid)
		{
			return;
		}
		
		
		foreach($drivers as $driver)
		{
			$qInsert = 'INSERT INTO ' . CHAMPSIGNUPS_TABLE . '
						 		(cs_no, cs_driver, cs_team, cs_champ, cs_div, cs_image, cs_car, cs_imageThmb, cs_entryOwner)
						VALUES (' . $currentEntry['cs_no'] . ', ' . $driver . ', ' . $currentEntry['cs_team'] . ', ' .
								   $currentEntry['cs_champ'] . ', ' . $currentEntry['cs_div'] . ', "' . $currentEntry['cs_image'] . '", ' .
								   $currentEntry['cs_car'] . ', "' . $currentEntry['cs_imageThmb'] . '", ' . $_POST['captainSelect'] . ')';
			$db->sql_query($qInsert);
		}
		
		$this->items[] = new addMessage($lang['UserCPMultiEntryDriversUpdated'],$lang['AdminUpdatedTitle']);
	}
	
	
	function setupEditMyChampionship()
	{
		global $db, $lang;
		include_once('includes/addMessage.php');
		
		$q = 'select c.c_id as champid, c.c_title, cs_no, d_id, d_title, c.c_teamChanging, c.c_carChanging, c.c_classChange, c.c_driversPerTeam, 
					 c.c_multipleCarsPerTeam, c.c_multiDriverEntryMin,
					(SELECT t.t_id FROM ' . TEAMS_TABLE . ' t WHERE t.t_id = cs_team LIMIT 0, 1) AS t_id,
					(SELECT t.t_name FROM ' . TEAMS_TABLE . ' t WHERE t.t_id = cs_team LIMIT 0, 1) AS t_name,  
					(SELECT count(*) FROM ' . CHAMPSIGNUPS_TABLE . ' cs2 WHERE cs2.cs_driver = cs2.cs_entryOwner AND cs2.cs_team = cs.cs_team AND cs2.cs_champ = c.c_id) AS team_count, 
					(SELECT ca.c_manufacturer FROM ' . CARS_TABLE . ' ca WHERE ca.c_id = cs_car LIMIT 0, 1) AS c_manufacturer,
					(SELECT ca.c_model FROM ' . CARS_TABLE . ' ca WHERE ca.c_id = cs_car LIMIT 0, 1) AS c_model,
					(SELECT ca.c_id FROM ' . CARS_TABLE . ' ca WHERE ca.c_id = cs_car LIMIT 0, 1) AS carid 
				 FROM ' . CHAMPIONSHIPS_TABLE .' c, ' . CHAMPSIGNUPS_TABLE . ' cs
				 LEFT JOIN ' . DIVISIONS_TABLE .' ON cs_div = d_id
				 WHERE cs_champ = c.c_id AND cs_driver = cs_entryOwner AND cs_driver = ' . $_SESSION["valid_id"] . ' AND cs_champ = ' . $_POST['champid'] .'
			  ORDER BY c.c_title ASC';
			  
		$res = $db->sql_query($q);
		if( $row = $db->sql_fetchrow($res))
		{
			if($row['d_id'] == '')
			{
				$row['d_id'] = 0;
				$row['d_title'] = $lang['Unassigned'];
			}
			
			$this->teams = $row;
			
			//informational message
			$infomess = $lang['ChampionshipRulesIntroduction'] . '<br><br>';
			$infomess .= $row['c_carChanging'] == 1 ? $lang['ChampionshipCarChangingYes'] . '<br>' : $lang['ChampionshipCarChangingNo'] . '<br>';
			$infomess .= $row['c_classChange'] == 1 ? $lang['ChampionshipClassChangingYes'] . '<br>' : $lang['ChampionshipClassChangingNo'] . '<br>';
			$infomess .= $lang['ChampionshipTeamChangingOpt' .$row['c_teamChanging']] . '<br>';
			$infomess .= $row['c_multipleCarsPerTeam'] == 1 ? $lang['ChampionshipOneMakePerTeamNo'] . 
								'<br>' : $lang['ChampionshipOneMakePerTeamYes'] . '<br>';
			$infomess .= $row['c_driversPerTeam'] > 0 ? str_replace('{numdrivers}',$row['c_driversPerTeam'],$lang['ChampionshipDriversPerTeamYes']) . '<br>':'';
			$infomess .= $row['c_multiDriverEntryMin'] > 0 ? $lang['ChampionshipMultiDrivers']:'';
			
			
			$this->items[] = new addMessage($infomess,$row['c_title']);
			
			//can change car?
			if($row['carid'] == '' || ($row['c_carChanging'] == 1 && ($row['team_count'] < 2 || $row['c_multipleCarsPerTeam'] == 1)))
			{
				if($row['carid'] == '')
				{
					$this->carOptions = '<option value="0" SELECTED>' . $row['Unassigned'] . '</option>';
				}
				else
				{
					$this->carOptions = '';
				}
				
				if($row['c_classChange'] == 1 )
				{
					$q_cars = 'SELECT c.c_id, c.c_model, c.c_manufacturer , d_title
							   FROM ' . CARS_TABLE . ' c, ' . CHAMP_CLASSES_TABLE . ' cl 
							   LEFT JOIN ' . DIVISIONS_TABLE . '
							   ON cl.c_defaultdiv = d_id
    	                	   WHERE c.c_class = cl.c_class AND cl.c_champid = ' .  $_POST['champid'] . '
							   ORDER BY c_manufacturer, c_model';
					$result = $db->sql_query($q_cars);
					while($car = $db->sql_fetchrow($result)) 
					{
						$this->carOptions .= '<option value="' . $car['c_id'] . '"' . ($row['carid'] == $car['c_id'] ? 'SELECTED' : '') . 
													'>' . $car['c_manufacturer'] . ' ' . $car['c_model'] . 
										 ($car['d_title'] == '' ? '' : ' (' . $lang['ChampSignupDivision'] . ': ' . $car['d_title'] . ')') .
										 '</option>';
					}
				}
				else
				{
					$q_cars = 'SELECT c.c_id, c.c_model, c.c_manufacturer 
							   FROM ' . CARS_TABLE . ' c, ' . CARS_TABLE . ' c2, ' . CHAMP_CLASSES_TABLE . ' cl 
    	                	   WHERE c.c_class = cl.c_class AND cl.c_champid = ' .  $_POST['champid'] . ' AND
							   		 c2.c_id = ' . $row['carid'] . ' AND c2.c_class = cl.c_class
							   ORDER BY c_manufacturer, c_model';
					$result = $db->sql_query($q_cars);
					while($car = $db->sql_fetchrow($result)) 
					{
						$this->carOptions .= '<option value="' . $car['c_id'] . '"' . ($row['carid'] == $car['c_id'] ? 'SELECTED' : '') . 
													'>' . $car['c_manufacturer'] . ' ' . $car['c_model'] . '</option>';
					}
				}
			}
			else
			{
				$this->carOptions = '<option value="' . $row['carid'] . '">' . $row['c_manufacturer'] . ' ' . $row['c_model'] . '</option>';
			}
			
			//can change team?
			if(($row['t_id'] == '' && $row['c_teamChanging'] == 1) || $row['c_teamChanging'] == 2)
			{
				$car = $row['c_carChanging'] == 1 || $row['carid'] == '' ? $lang['AnyCar'] : $row['c_manufacturer'] . ' ' . $row['c_model'];
				
				if($row['c_multiDriverEntryMin'] == 0)
					$this->teamOptions = '<option value="0"' . ($row['t_id'] == 0 ? 'SELECTED' : '') . '>' . $lang['Independent'] . ' (' . $car . ')</option>';
				
				$q_teams = 'SELECT t_id, t_name, ' . 
						'(SELECT CONCAT(c_manufacturer," ", c_model) FROM ' . CHAMPSIGNUPS_TABLE . ', ' . CARS_TABLE . 
							' WHERE cs_driver = cs_entryOwner AND  c_id = cs_car AND cs_team = t_id AND cs_champ = ' . $_POST['champid'] . ' LIMIT 0, 1) as t_car, ' .
						'(SELECT c_id FROM ' . CHAMPSIGNUPS_TABLE . ', ' . CARS_TABLE . 
							' WHERE cs_driver = cs_entryOwner AND  c_id = cs_car AND cs_team = t_id AND cs_champ = ' . $_POST['champid'] . ' LIMIT 0, 1) as t_carid, ' .
						'(SELECT count(*) FROM ' . CHAMPSIGNUPS_TABLE . ' WHERE cs_driver = cs_entryOwner AND cs_team = t_id AND cs_champ = ' . $_POST['champid'] . 
							' LIMIT 0, 1) as tm_entries ' .
						' FROM ' . TEAMS_TABLE . ', ' . TEAMMEMBERS_TABLE . ' WHERE (t_id = tm_team or tm_team = t_parent) AND tm_approved = 1 AND tm_driver = ' . 
						$_SESSION['valid_id'] .' 
						GROUP BY t_id
						ORDER BY t_name';
						
				$result = $db->sql_query($q_teams);
				while($t = $db->sql_fetchrow($result)) 
				{
					//we haven't full filled our quota
					if($row['c_driversPerTeam'] == 0 || $row['c_driversPerTeam'] > $t['tm_entries'] || $row['t_id'] == $t['t_id'])
					{
						if($row['c_multipleCarsPerTeam'] == 1)
						{
							$this->teamOptions .= '<option value="' . $t['t_id'] . '" ' . ($row['t_id'] == $t['t_id'] ? 'SELECTED' : '') . '>' . 
														$t['t_name']  . ' ('. $lang['AnyCar'].')</option>';
						}
						else
						{
							//can only switch to a newly formed team or one presently running the same car
							if($row['c_carChanging']==0)
							{
								if($t['t_carid'] == '' || $t['t_carid'] == $row['carid'])
								{	
									$this->teamOptions .= '<option value="' . $t['t_id'] . '"' . ($row['t_id'] == $t['t_id'] ? 'SELECTED' : '') . 
														'>' . $t['t_name']  . ' (' . $row['c_manufacturer'] . ' ' . $row['c_model'] . ')</option>';
								}
							}
							//we can switch teams but we must use their car
							else
							{
								if($row['t_id'] == $t['t_id'] && $t['tm_entries'] == 1)
								{
									$car = $lang['AnyCar'];
								}
								else
								{
									$car = $t['t_carid'] == '' ? $lang['AnyCar'] : $t['t_car'];
								}
								$this->teamOptions .= '<option value="' . $t['t_id'] . '"' . ($row['t_id'] == $t['t_id'] ? 'SELECTED' : '') . 
																'>' . $t['t_name']  . ' (' . $car . ')</option>';
							}
						}
					}
				}
			}
			else
			{
				if($row['t_id'] == 0)
				{
					$this->teamOptions = '<option value="0">' . $lang['Independent'] . '</option>';
				}
				else
				{
					$this->teamOptions = '<option value="' . $row['t_id'] . '"SELECTED>' . $row['t_name'] . '</option>';
				}
			}
			
			include('includes/imageUpload.php');
			$this->logoManager = new imageUpload('champimage', $_POST['champid']);
		}		
	}
	
	
	function setupEditMyChampionshipDrivers()
	{
		global $db, $lang;
		include_once('includes/addMessage.php');
		
		$team_parent = $_POST['teamid'];
		$q = 'SELECT t_parent FROM lc_teams l WHERE t_id = ' . $_POST['teamid'];
		$res = $db->sql_query($q);
		if( $row = $db->sql_fetchrow($res))
		{
			if($row['t_parent'] > 0)
			{
				$team_parent = $row['t_parent'];
			}
		}
		
		
		$q = 'SELECT user_id, pf_drivername, cs_entryOwner, cs_no, cs_div, cs_image, cs_car, cs_imageThmb
			  FROM ' . DRIVERNAME_TABLE . '
			  LEFT JOIN ' . TEAMMEMBERS_TABLE . ' ON  (user_id = tm_driver AND tm_team = ' . $team_parent . ' )
			  LEFT JOIN ' . CHAMPSIGNUPS_TABLE . ' ON (cs_driver = user_id AND cs_champ = ' . $_POST['champid'] . ')
			  WHERE ((tm_team = ' . $team_parent . ' AND user_id = tm_driver ) or (cs_champ = ' . $_POST['champid'] . ' AND cs_entryOwner = ' . $_SESSION['valid_id'] . '))
			  		AND (cs_entryOwner = ' . $_SESSION['valid_id'] . ' or cs_entryOwner is null)
			  GROUP BY user_id
			  ORDER BY pf_drivername ASC';
		$res = $db->sql_query($q);
		while( $row = $db->sql_fetchrow($res))
		{
			$this->drivers[] = $row;
			
			if($row['user_id'] == $row['cs_entryOwner'])
			{
				$this->teams = $row;
			}
		}
		
		$q = 'SELECT c_multiDriverEntryMin, c_multiDriverEntryMax FROM ' . CHAMPIONSHIPS_TABLE . ' WHERE c_id = ' . $_POST['champid'];
		$res = $db->sql_query($q);
		if( $row = $db->sql_fetchrow($res))
		{
			$this->teams['driverMin'] = $row['c_multiDriverEntryMin'];
			$this->teams['driverMax'] = $row['c_multiDriverEntryMax'];
		}
		
		$this->items[] = new addMessage(sprintf($lang['UserCPMultiEntryDriversInfo'], $this->teams['driverMin'], $this->teams['driverMax']), $lang['UserCPMultiEntryDrivers']);
	}
	
	
	function renderMyTeams()
	{
		global $lang, $skin_dir;
		
		include $skin_dir . 'tpl/tableStart.tpl';
		$teamid = -1;
		foreach($this->teams as $team)
		{
			$teamid = $team['t_id'];
			$teamname = '<a href="teams.php?id=' . $team['t_id'] . '">' . StripSlashes($team['t_name']) . '</a>';
			if($team['tm_approved'] == 1)
			{
				$memberinfo = $team['tm_admin'] == 1 ? $lang['TeamAdmin'] : $lang['TeamApproved'];
			}
			else
			{
				$memberinfo = $lang['TeamPendingApproval'];
			}
			
			include $skin_dir . 'tpl/usercpTeamInfo.tpl';
		}
		
		if($teamid == -1)
		{
			echo '<tr><td class="tableButtonLeft">'. $lang['UserCPNoEntries'] . '</td></tr>';
		}
		
		include $skin_dir . 'tpl/tableEnd.tpl';
		
	}
	
	function renderEditMyChampionships()
	{
		global $lang, $skin_dir;
			
		$champid = $this->teams['champid'];
			
		if($this->teams['d_title'] == $this->teams['c_title'])
		{
			$division = '';
		}
		else
		{
			$division = ' (' . $this->teams['d_title'] . ')';
		}
				
		$champname = '<a href="championships.php?id=' . $this->teams['champid'] . '">' . StripSlashes($this->teams['c_title'] . $division) . '</a>';
		
		$teamOptions = $this->teamOptions;
		$carOptions = $this->carOptions;
			
		$carno = $this->teams['cs_no'] == 0 ? 'N/A' :  $this->teams['cs_no'];
			
		include $skin_dir . 'tpl/usercpChampEdit.tpl';
		
		
		if($this->logoManager != '')
		{
			$this->logoManager->render();
		}
		
	}
	
	
	function renderEditMyChampionshipDrivers()
	{
		global $lang, $skin_dir;
		
		$minDrivers = $this->teams['driverMin'];
		$maxDrivers = $this->teams['driverMax'];
		$action = 'usercp.php?action=mychampionships';
		$champid = $_POST['champid'];
		$orgCaptain = $this->teams['user_id'];
		$teamid = $_POST['teamid'];
		
		include $skin_dir . 'tpl/multiDriversStart.tpl';
		$x = 0;
		foreach($this->drivers as $driver)
		{
			$driver['driverCount'] = $x;
			$driver['driverChecked'] = $driver['cs_entryOwner'] > 0 ? 'CHECKED' : '';
			$driver['captainChecked'] = $driver['cs_entryOwner'] == $driver['user_id']  ? 'CHECKED' : '';
			$driver['captainEnabled'] = $driver['driverChecked'] == '' ? 'DISABLED' : '';
			include $skin_dir . 'tpl/multiDriversEntry.tpl';
			$x++;
		}
		$submitName = 'multiDriverEntry';
		include $skin_dir . 'tpl/multiDriversEnd.tpl';		
	}
	
	function renderMyChampionships()
	{
		global $lang, $skin_dir;
		include $skin_dir . 'tpl/tableStart.tpl';
		$champid = -1;
		foreach($this->teams as $champ)
		{
			$champid = $champ['champid'];
			
			$remEditStart = $champ['c_active']  == 0 || $champ['cs_driver'] != $champ['cs_entryOwner'] ? '<!--' : '';			
			$remEditEnd = $champ['c_active'] == 0 || $champ['cs_driver'] != $champ['cs_entryOwner'] ? '-->' : '';
			
			$remDriversStart = $champ['c_multiDriverEntryMin'] == 0 || $champ['cs_driver'] != $champ['cs_entryOwner'] ? '<!--' : '';			
			$remDriversEnd = $champ['c_multiDriverEntryMin'] == 0 || $champ['cs_driver'] != $champ['cs_entryOwner'] ? '-->' : '';
			
				
			if($champ['d_title'] == $champ['c_title'])
			{
				$champname = '<a href="championships.php?id=' . $champ['champid'] . '">' . StripSlashes($champ['c_title']) . '</a>';
			}
			else
			{
				$champname = '<a href="championships.php?id=' . $champ['champid'] . '">' . StripSlashes($champ['c_title'] . '<br>' . $champ['d_title']) . '</a>';
			}
			
			
			if($champ['t_id'] != '')
			{
				$team = '<a href="teams.php?id=' . $champ['t_id'] . '">' . StripSlashes($champ['t_name']) . '</a>';
			}
			else
			{
				$team = $lang['Independent'];
			}
			if($champ['carid'] != '')
			{
				$car = '<a href="cars.php?id=' . $champ['carid'] . '">' . StripSlashes($champ['c_manufacturer'] . ' ' . $champ['c_model']) . '</a>';
			}
			else
			{
				$car = $lang['Unassigned'];
			}
			
			$teamid = $champ['t_id'];
			$number = $champ['cs_no'] == 0 ? '' : '#' . $champ['cs_no'];
			
			$car = $number . ' ' . $car . '<br>' . $team ;
			
			include $skin_dir . 'tpl/usercpChampInfo.tpl';
		}
		
		if($champid == -1)
		{
			echo '<tr><td class="tableButtonLeft">'. $lang['UserCPNoEntries'] . '</td></tr>';
		}
		
		include $skin_dir . 'tpl/tableEnd.tpl';
	}
	
	function setupTeamAdmin()
	{
		global $db, $lang;
		include_once('includes/addMessage.php');
		include_once('includes/editBlock.php');
		
				
		$this->items[] = new addMessage($lang['UserCPTeamsAdminInfo'],$lang['UserCPTeamsAdmin']);
		if(isset($_POST['itemID']) && is_numeric($_POST['itemID']))
		{
			
			if($this->isTeamAdmin($_POST['itemID']))
			{
				$this->items[] = new editBlock('usercp.php?action=teamadmin',  'Teams', 
											  'SELECT t_id, t_name FROM ' . TEAMS_TABLE . ', ' . TEAMMEMBERS_TABLE . ' WHERE (t_id = tm_team OR t_parent = tm_team) ' .
											  'AND tm_admin = 1 AND tm_driver = ' . $_SESSION["valid_id"] . ' GROUP BY t_id ORDER BY t_name',
											  't_id', 't_name', '', false, $_POST['itemID']);
											  
				$q = 'SELECT t.*, p.t_name as parent_name, p.t_id as parent_id
					  FROM ' . TEAMS_TABLE . ' t LEFT JOIN ' . TEAMS_TABLE . ' p ON t.t_parent = p.t_id
					  WHERE t.t_id = ' . $_POST['itemID'];
				$res = $db->sql_query($q);
				if( $this->teams = $db->sql_fetchrow($res))
				{
					if(is_numeric($this->teams['parent_id']))
					{
						$this->teams['ParentOptions'] = '<option value="' . $this->teams['parent_id'] . '">' . $this->teams['parent_name'] . '</option>';
					}
					else
					{
						$this->teams['ParentOptions'] = '<option value="0">' . $lang['TeamParent'] . '</option>';
					}
					$q = 'SELECT u.user_id, pf_drivername as user_drivername, tm_admin, tm_approved 
						  FROM ' . USERS_TABLE . ' u, '. DRIVERNAME_TABLE . ' d, ' . TEAMMEMBERS_TABLE .
							' WHERE u.user_id = d.user_id AND tm_driver = u.user_id AND tm_team = ' . $_POST['itemID'];
					$res = $db->sql_query($q);
					while( $row = $db->sql_fetchrow($res))
					{
						$this->drivers[] = $row;
					}
					include('includes/imageUpload.php');
					$this->valid = true;
					$this->items[] = new addMessage($lang['UserCPEditTeamInfo'], $lang['UserCPEditTeam']);
					$this->logoManager = new imageUpload('teams', $_POST['itemID']);
				}
				else
				{
					$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
				}
			}
			else
			{
				$this->items[] = new addMessage($lang['ErrorInsufficientPermissions'], $lang['ErrorTitle']);
			}
										  
		}
		else
		{
			$this->items[] = new editBlock('usercp.php?action=teamadmin',  'Teams', 
										  'SELECT t_id, t_name FROM ' . TEAMS_TABLE . ', ' . TEAMMEMBERS_TABLE . ' WHERE (t_id = tm_team OR t_parent = tm_team)  ' .
										  'AND tm_admin = 1 AND tm_driver = ' . $_SESSION["valid_id"] . ' GROUP BY t_id ORDER BY t_name',
										  't_id', 't_name', '', false);			
										  
			$this->items[] = new addMessage($lang['UserCPCreateTeamInfo'], $lang['UserCPCreateTeam']);
			$this->add = true;
			$this->valid = true;
			$this->teams['t_id'] = '';
			$this->teams['t_name'] = '';
			$this->teams['t_nationality'] = '';
			$this->teams['t_website'] = '';
			$this->teams['t_description'] = '';
			$this->teams['ParentOptions'] = '<option value="0">' . $lang['TeamParent'] . '</option>';
			
			$q = 'SELECT t_name, t_id 
				  FROM ' . TEAMS_TABLE . ', ' . TEAMMEMBERS_TABLE . '
				  WHERE tm_admin = 1 AND t_parent = 0 AND tm_team = t_id AND tm_driver = ' . $_SESSION['valid_id'] . '
				  ORDER BY t_name';
			
			$res = $db->sql_query($q);
			while( $row = $db->sql_fetchrow($res))
			{
				$this->teams['ParentOptions'] .= '<option value="' . $row['t_id'] . '">' . $row['t_name'] . '</option>';
			}
		}
		
		
	}
	
	function isTeamAdmin($teamid)
	{
		global $db;
	
		$q = 'SELECT tm_driver FROM ' . TEAMMEMBERS_TABLE . ', ' . TEAMS_TABLE . ' WHERE tm_admin = 1 AND tm_driver = ' . $_SESSION["valid_id"] .
				' AND ((t_id = tm_team AND tm_team = ' . $teamid . ') OR (t_parent = tm_team AND t_id = ' . $teamid . '))';
		$res = $db->sql_query($q);
		if( $row = $db->sql_fetchrow($res))
		{
			return true;
		}
		else
		{
			return false;
		}
		
	}
	
	function renderTeamAdmin()
	{
		global $lang, $skin_dir;
		
		if($this->valid)
		{
			$row = $this->teams;
			$row['t_name'] = StripSlashes($row['t_name']);
			
			
			if($this->add)
			{
				$submitValue = 'addTeamDetails';
				$submitText = $lang['AddButton'];
			}
			else
			{
				$submitValue = 'editTeamDetails';
				$submitText = $lang['SaveButton'];
			}
			$mess = new addMessage('', StripSlashes($lang['TeamDetails']), true);
			$mess->render();
			include $skin_dir . 'tpl/usercpAdminTeamInfo.tpl';
			
			if(! $this->add)
			{
				$mess = new addMessage('', $lang['TeamDrivers'], true);
				$mess->render();
				
				echo '<table class="contentTable" border="0">';
				$teamid = $row['t_id'];
				foreach($this->drivers as $driver)
				{
					$drivername = StripSlashes($driver['user_drivername']);
					$driverid = $driver['user_id'];
					$admin_checked = $driver['tm_admin'] == 1 ? 'CHECKED' : '';
					$approved_checked = $driver['tm_approved'] == 1 ? 'CHECKED' : '';
					include $skin_dir . 'tpl/usercpAdminTeamDriver.tpl';
				}
				echo '</table>';	
				
				if($this->logoManager != '')
				{
					$this->logoManager->render();
				}
				
			}
		}		
	}
	
	
	function renderItems()
	{
		foreach($this->items as $value)
		{
			$value->render();
		}
	}
}

?>